<template>
  <div class="flex">
    <el-card class="w-12/100 user" :gutter="12" shadow="always">
      <el-input v-model="filterText" placeholder="栏目名称或ID" />
      <el-row  justify="space-between" >
      <el-link type="primary" @click="handleSelectAllClick">{{
        $t('cms.content.channel.allChannel')
      }}</el-link>
      <el-link type="primary" style="margin-right: 2px;" @click="handleFoldAndExplain">{{
        $t('cms.content.channel.expand')
      }}</el-link>
      </el-row>
      <el-scrollbar height="650">
        <el-tree
          ref="treeRef"
          node-key="id"
          :default-expand-all="defaultExpandAll"
          :data="channelOptions"
          :props="defaultProps"
          :highlight-current="true"
          :filter-node-method="filterNode"
          :expand-on-click-node="false"
          @node-click="handleChannelNodeClick"
        />
      </el-scrollbar>
    </el-card>
    <el-card class="w-88/100 user" style="margin-left: 10px" :gutter="12" shadow="hover">
      <!-- 搜索工作栏 -->
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
          ><el-form-item label="标题" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入标题"
              clearable
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              class="!w-120px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CMS_CONTENT_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="置顶" prop="topLevel">
            <el-select
              v-model="queryParams.topLevel"
              placeholder="请选择置顶"
              clearable
              class="!w-120px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CMS_OPEN_CLOSE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="标记" prop="dictMark">
            <el-select
              v-model="queryParams.dictMark"
              placeholder="请选择标记"
              clearable
              class="!w-120px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CMS_CONTENT_MARKS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="区块" prop="dictBlock">
            <el-select
              v-model="queryParams.dictBlock"
              placeholder="请选择区块"
              clearable
              class="!w-120px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.CMS_CONTENT_BLOCKS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="发布时间" prop="releaseTime">
            <el-date-picker
              v-model="queryParams.releaseTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item>
            <el-select
v-model="queryParams.orderStrs" 
            class="!w-160px">
              <el-option
                v-for="n in [1, 2, 3, 4,5]"
                :key="n"
                :label="t(`cms.content.orderBy.${n}`)"
                :value="t(`cms.content.orderByVal.${n}`)"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"
              ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
            >
            <el-button @click="resetQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button
            >
          </el-form-item>
          <el-form-item>
            <!-- 操作：新增 -->
            <XButton
              type="primary"
              preIcon="ep:zoom-in"
              :title="t('action.add')"
              v-hasPermi="['cms:content:create']"
              @click="handleCreate()"
            />
            <el-dropdown
              class="p-1"
              v-hasPermi="['cms:content:archive', 'cms:content:top', 'cms:content:mark']"
            >
              <el-button type="primary" postIcon="ep:arrow-down">{{
                t('common.batchAction')
              }}</el-button>
              <template #dropdown>
                <el-dropdown-item>
                  <!-- 操作：删除 -->
                  <XTextButton
                    preIcon="ep:delete"
                    :title="t('cms.content.op.delete')"
                    v-hasPermi="['cms:content:delete']"
                    @click="submitBatch('delete')"
                  />
                </el-dropdown-item>
                <el-dropdown-item>
                  <!-- 操作：彻底删除 -->
                  <XTextButton
                    preIcon="ep:delete"
                    :title="t('cms.content.op.twoDelete')"
                    v-hasPermi="['cms:content:delete']"
                    @click="submitBatch('twoDelete')"
                  />
                </el-dropdown-item>
                <el-dropdown-item>
                  <!-- 操作：下线 -->
                  <XTextButton
                    preIcon="ep:arrow-down-bold"
                    :title="t('cms.content.op.offline')"
                    v-hasPermi="['cms:content:offline']"
                    @click="submitBatch('offline')"
                  />
                </el-dropdown-item>
                <el-dropdown-item>
                  <!-- 操作：发布 -->
                  <XTextButton
                    preIcon="ep:promotion"
                    :title="t('cms.content.op.publish')"
                    v-hasPermi="['cms:content:publish']"
                    @click="submitBatch('publish')"
                  />
                </el-dropdown-item>
                <el-dropdown-item>
                  <!-- 操作：归档 -->
                  <XTextButton
                    preIcon="ep:box"
                    :title="t('cms.content.op.archive')"
                    v-hasPermi="['cms:content:archive']"
                    @click="submitBatch('archive')"
                  />
                </el-dropdown-item>
                <el-dropdown-item>
                  <!-- 操作：标记 -->
                  <XTextButton
                    preIcon="ep:star-filled"
                    :title="t('cms.content.op.mark')"
                    v-hasPermi="['cms:content:mark']"
                    @click="submitBatch('mark')"
                  />
                </el-dropdown-item>
                <el-dropdown-item>
                  <!-- 操作：区块设置 -->
                  <XTextButton
                    preIcon="ep:memo"
                    :title="t('cms.content.op.block')"
                    v-hasPermi="['cms:content:block']"
                    @click="submitBatch('block')"
                  />
                </el-dropdown-item>
                <el-dropdown-item>
                  <!-- 操作：移动 -->
                  <XTextButton
                    preIcon="ep:document-remove"
                    :title="t('cms.content.op.move')"
                    v-hasPermi="['cms:content:move']"
                    @click="submitBatch('move')"
                  />
                </el-dropdown-item>
                <el-dropdown-item>
                  <!-- 操作：复制 -->
                  <XTextButton
                    preIcon="ep:copy-document"
                    :title="t('cms.content.op.copy')"
                    v-hasPermi="['cms:content:copy']"
                    @click="submitBatch('copy')"
                  />
                </el-dropdown-item>
                <el-dropdown-item v-if="useUserStore().grade >= 1">
                  <!-- 操作：推送 -->
                  <XTextButton
                    preIcon="ep:document"
                    :title="t('cms.content.op.push')"
                    v-hasPermi="['cms:content:push']"
                    @click="submitBatch('push')"
                  />
                </el-dropdown-item>
              </template>
            </el-dropdown>
          </el-form-item>
        </el-form>
      </ContentWrap>
      <!--新增和批量操作-->
      <!-- 列表 -->
      <ContentWrap>
        <el-table
          v-loading="loading"
          :data="list"
          :table-layout="tableLayout"
          ref="tableRef"
          row-key="id"
          @selection-change="handleDataSelectionChange"
          style="width: 100%"
        >
          <el-table-column type="selection" />
          <el-table-column label="ID" align="center" prop="id" />
          <el-table-column
            label="标题"
            align="center"
            prop="title"
            width="600px"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <div style="text-align: left">
                <el-link :href="row.url" target="_blank"> {{ row.title }}</el-link>
                <el-tooltip v-if="row.topLevel > 0" placement="top-start">
                  <template #content>
                    {{ row.topLevel }}
                  </template>
                  <el-icon><Top /></el-icon>
                </el-tooltip>
                <DictTag
                  :type="DICT_TYPE.CMS_CONTENT_MARKS"
                  :value="row.dictMark"
                  v-if="row.dictMark"
                />
                <DictTag
                  :type="DICT_TYPE.CMS_CONTENT_BLOCKS"
                  :value="row.dictBlock"
                  v-if="row.dictBlock"
                />
                <el-tooltip v-if="row.originContentId" placement="top-start">
                  <template #content>
                    <el-icon class="ml-1 align-middle"><DocumentCopy /></el-icon>
                    {{ t(`cms.content.type.${row.createMode}`) }}:
                    <span v-if="row.siteId !== row.originContent.siteId"
                      >[{{ row.originContent.siteName }}]</span
                    >
                    {{ row.originContent.nodeNames.map((it: any) => it).join('>') }}
                  </template>
                  <el-icon><DocumentCopy /></el-icon>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="栏目" align="center" prop="channelName" />
          <el-table-column
v-if="!['create_time_desc','create_time_asc'].includes(queryParams.orderStrs)"
            label="发布时间"
            align="center"
            prop="releaseTime"
            :formatter="dateFormatter"
          />
          <el-table-column
v-if="['create_time_desc','create_time_asc'].includes(queryParams.orderStrs)"
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
          />
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.CMS_CONTENT_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="280px">
            <template #default="{ row }">
              <!-- 操作：修改 -->
              <XTextButton
                preIcon="ep:edit"
                v-if="row.editable"
                v-hasPermi="['cms:content:update']"
                :title="t('action.edit')"
                @click="handleEdit(row.id)"
              />
              <!--发布-->
              <XTextButton
                preIcon="ep:promotion"
                v-if="!row.processDefinitionId && ![2,1].includes(row.status)"
                :title="t('cms.content.op.publish')"
                v-hasPermi="['cms:content:publish']"
                @click="handlePublish([row.id])"
              />
              <!--下线-->
              <XTextButton
                preIcon="ep:arrow-down-bold"
                v-if="[1].includes(row.status)"
                :title="t('cms.content.op.offline')"
                v-hasPermi="['cms:content:offline']"
                @click="handleOffline([row.id])"
              />
              <!-- 操作：删除 -->
              <XTextButton
                preIcon="ep:delete"
                v-if="![7].includes(row.status)"
                :title="t('action.del')"
                v-hasPermi="['cms:content:delete']"
                @click="handleDelete([row.id])"
              />
              <XTextButton
                preIcon="ep:delete"
                v-if="[7].includes(row.status)"
                :title="t('cms.content.op.twoDelete')"
                v-hasPermi="['cms:content:delete']"
                @click="handleTwoDelete([row.id])"
              />
              <el-dropdown
                class="p-0.5"
                v-hasPermi="['cms:content:archive', 'cms:content:top', 'cms:content:mark']"
              >
                <XTextButton :title="t('action.more')" postIcon="ep:arrow-down" />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>
                      <!-- 操作：置顶 -->
                      <XTextButton
                        preIcon="ep:top"
                        :title="t('cms.content.op.top')"
                        v-hasPermi="['cms:content:top']"
                        @click="handleTop([row.id], row.topLevel)"
                      />
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <!-- 操作：标记 -->
                      <XTextButton
                        preIcon="ep:star-filled"
                        :title="t('cms.content.op.mark')"
                        v-hasPermi="['cms:content:mark']"
                        @click="handleMark([row.id])"
                      />
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <!-- 操作：区块设置 -->
                      <XTextButton
                        preIcon="ep:memo"
                        :title="t('cms.content.op.block')"
                        v-hasPermi="['cms:content:block']"
                        @click="handleBlock([row.id])"
                      />
                    </el-dropdown-item>
                    <!-- 操作：审核进度 -->
                    <XTextButton
                      preIcon="ep:edit-pen"
                      :title="t('cms.content.op.auditprocess')"
                      v-if="row.processInstanceId"
                      @click="handleAudit(row)"
                    />
                    <el-dropdown-item>
                      <!-- 操作：移动 -->
                      <XTextButton
                        preIcon="ep:document-remove"
                        :title="t('cms.content.op.move')"
                        v-hasPermi="['cms:content:move']"
                        @click="handleMove([row.id])"
                      />
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <!-- 操作：复制 -->
                      <XTextButton
                        preIcon="ep:copy-document"
                        :title="t('cms.content.op.copy')"
                        v-hasPermi="['cms:content:copy']"
                        @click="handleCopy([row.id])"
                      />
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <!-- 操作：推送 -->
                      <XTextButton
                        preIcon="ep:document"
                        :title="t('cms.content.op.push')"
                        v-hasPermi="['cms:content:push']"
                        @click="handlePush([row.id])"
                      />
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <!-- 操作：内容版本 -->
                      <XTextButton
                        preIcon="ep:document"
                        :title="t('action.version')"
                        v-hasPermi="['cms:content-version:query']"
                        @click="handleVersion(row.id)"
                      />
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <!-- 操作：相关内容 -->
                      <XTextButton
                        preIcon="ep:share"
                        :title="t('cms.content.op.relate')"
                        v-hasPermi="['cms:content-relate:create']"
                        @click="handleRelate(row.id)"
                      />
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <!-- 操作：归档 -->
                      <XTextButton
                        preIcon="ep:box"
                        v-if="[1].includes(row.status)"
                        :title="t('cms.content.op.archive')"
                        v-hasPermi="['cms:content:archive']"
                        @click="handleArchive([row.id])"
                      />
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-card>
  </div>
  <!--添加 修改 弹窗 -->
  <ContentForm
    v-model="formVisible"
    :action="action"
    :bean-id="beanId"
    :channel="channel"
    @finished="finishAndReload"
  />
  <!--移动栏目 -->
  <Dialog v-model="moveDialogVisible" :title="t('cms.content.op.move')" width="30%">
    <el-form :model="contentMove" label-width="100px" :inline="true">
      <el-form-item :label="t('cms.content.channel')">
        <el-input v-model="filterText" placeholder="栏目名称或ID" />
        <el-scrollbar height="450">
          <el-tree
            ref="treeRef"
            node-key="id"
            :default-expand-all="defaultExpandAll"
            :data="channelOptions"
            :props="defaultProps"
            :highlight-current="true"
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            @node-click="handleMoveChannelNodeClick"
          />
        </el-scrollbar>
      </el-form-item>
    </el-form>
    <!-- 操作按钮 -->
    <!-- 按钮：保存 -->
    <XButton type="primary" :title="t('cms.content.op.move')" @click="moveChannel()" />
    <!-- 按钮：关闭 -->
    <XButton :title="t('dialog.close')" @click="moveDialogVisible = false" />
  </Dialog>
  <!--标记-->
  <Dialog v-model="markDialogVisible" :title="t('cms.content.op.mark')" width="30%">
    <el-form :model="contentMark" label-width="140px" :inline="true">
      <el-form-item :label="t('cms.content.contentMark')" prop="contentMark.dictMark">
        <el-select v-model="contentMark.dictMark"   class="!w-160px">
          <el-option :label="t('common.selectText')" value="" />
          <el-option
            v-for="item in contentMarks"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <!-- 操作按钮 -->
    <template #footer>
      <!-- 按钮：保存 -->
      <XButton type="primary" :title="t('cms.content.op.mark')" @click="markContent()" />
      <!-- 按钮：关闭 -->
      <XButton :title="t('dialog.close')" @click="markDialogVisible = false" />
    </template>
  </Dialog>
  <!--设置区块-->
  <Dialog v-model="blockDialogVisible" :title="t('cms.content.op.block')" width="30%">
    <el-form :model="contentBlock" label-width="100px" :inline="true">
      <el-form-item :label="t('cms.content.block')" prop="contentBlock.dictBlock">
        <el-select v-model="contentBlock.dictBlock"  class="!w-160px">
          <el-option :label="t('common.selectText')" value="" />
          <el-option
            v-for="item in contentBlocks"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <!-- 操作按钮 -->
    <template #footer>
      <!-- 按钮：保存 -->
      <XButton type="primary" :title="t('cms.content.op.block')" @click="blockContent()" />
      <!-- 按钮：关闭 -->
      <XButton :title="t('dialog.close')" @click="blockDialogVisible = false" />
    </template>
  </Dialog>
  <!--复制-->
  <Dialog v-model="copyDialogVisible" :title="t('cms.content.op.copy')" width="30%">
    <el-form :model="contentCopy" label-width="100px" :inline="true">
      <el-form-item :label="t('cms.content.copyType')" prop="contentCopy.pushType">
        <el-radio-group v-model="contentCopy.pushType" class="w-full">
          <el-radio
            v-for="item in contentPushTypes"
            :key="item.value"
            :label="item.value"
            :value="item.value"
            size="large"
            >{{ item.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="t('cms.content.channel')">
        <el-input v-model="filterText" placeholder="栏目名称或ID" />
        <el-scrollbar max-height="450">
          <el-tree
            ref="treeRef"
            node-key="id"
            :default-expand-all="defaultExpandAll"
            :data="channelOptions"
            :props="defaultProps"
            :highlight-current="true"
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            @node-click="handleCopyChannelNodeClick"
          />
        </el-scrollbar>
      </el-form-item>
    </el-form>
    <!-- 操作按钮 -->
    <template #footer>
      <!-- 按钮：保存 -->
      <XButton type="primary" :title="t('cms.content.op.copy')" @click="copySubmit()" />
      <!-- 按钮：关闭 -->
      <XButton :title="t('dialog.close')" @click="copyDialogVisible = false" />
    </template>
  </Dialog>
  <!--推送-->
  <Dialog v-model="pushDialogVisible" :title="t('cms.content.op.push')" width="30%">
    <el-form :model="contentPush" label-width="100px" :inline="true">
      <el-col :span="24">
        <el-form-item :label="t('cms.content.copyType')" prop="contentPush.pushType">
          <el-radio-group v-model="contentPush.pushType" class="w-full">
            <el-radio
              v-for="item in contentPushTypes"
              :key="item.value"
              :label="item.value"
              :value="item.value"
              size="large"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item></el-col
      >
      <el-col :span="24">
        <el-form-item
          :label="t('cms.content.push.targetSite')"
          :rules="{ required: true, message: () => t('common.required') }"
        >
          <el-select
v-model="contentPush.targetSiteId" @change="getPushChannelTree" 
 style="width: 260px"
>
            <el-option
              v-for="item in pushTargetSites"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select> </el-form-item
      ></el-col>
      <el-col :span="24">
        <el-form-item
          :label="t('cms.content.channel')"
          :rules="{ required: true, message: () => t('common.required') }"
        >
          <el-input
            v-model="filterText"
            placeholder="栏目名称或ID"
            v-if="pushChannelOptions !== undefined && pushChannelOptions.length > 0"
          />
          <el-scrollbar
            max-height="450"
            v-if="pushChannelOptions !== undefined && pushChannelOptions.length > 0"
          >
            <el-tree
              ref="treeRef"
              node-key="id"
              :default-expand-all="defaultExpandAll"
              :data="pushChannelOptions"
              :props="defaultProps"
              :highlight-current="true"
              :filter-node-method="filterNode"
              :expand-on-click-node="false"
              @node-click="handlePushChannelNodeClick"
            />
          </el-scrollbar> </el-form-item></el-col
      ><el-col :span="24">
        <el-form-item :label="t('cms.content.push.targetStatus')">
          <el-select v-model="contentPush.targetStatus"  class="!w-160px">
            <el-option
              v-for="item in contentStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            /> </el-select></el-form-item
      ></el-col>
      <el-col :span="24">
        <el-form-item
          :label="t('cms.content.push.pass')"
          :rules="{ required: true, message: () => t('common.required') }"
        >
          <el-input
            v-model="contentPush.pushPass"
            type="password"
            :placeholder="t('cms.content.push.pass.placeholder')"
            show-password
          />
        </el-form-item>
      </el-col>
    </el-form>
    <!-- 操作按钮 -->
    <template #footer>
      <!-- 按钮：保存 -->
      <XButton type="primary" :title="t('cms.content.op.push')" @click="pushSubmit()" />
      <!-- 按钮：关闭 -->
      <XButton :title="t('dialog.close')" @click="pushDialogVisible = false" />
    </template>
  </Dialog>
  <!--相关内容-->
  <Dialog v-model="relateDialogVisible" :title="t('cms.content.op.relate')" width="80%">
    <ContentWrap>
      <XButton
        type="primary"
        preIcon="ep:zoom-in"
        :title="t('action.add')"
        v-hasPermi="['cms:content-relate:create']"
        @click="handleRelateAdd()"
      />
      <el-table
        v-loading="relateLoading"
        :table-layout="tableLayout"
        :data="relateDatas"
        ref="relateTableRef"
        row-key="id"
      >
        <el-table-column label="标题" align="center" prop="relateTitle" />
        <el-table-column label="栏目" align="center" prop="channelName" />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
        />
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <!-- 操作：删除数据 -->
            <XTextButton
              v-hasPermi="['cms:content-relate:create']"
              preIcon="ep:delete"
              :title="t('action.del')"
              @click="contentRelateDeleteData(row.id)"
            />
            <XTextButton
              preIcon="ep:top"
              :title="t('cms.content.op.up')"
              v-if="getRowIndex(row) != 0"
              @click="handleRelateUp(row, getRowIndex(row), 1)"
            />
            <XTextButton
              preIcon="ep:bottom"
              :title="t('cms.content.op.down')"
              v-if="!getRowIndexIsEnd(row)"
              @click="handleRelateUp(row, getRowIndex(row), -1)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="relateTotal"
        v-model:page="relateQueryParams.pageNo"
        v-model:limit="relateQueryParams.pageSize"
        @pagination="getContentRelateList"
      />
    </ContentWrap>
  </Dialog>
  <!--选择相关内容-->
  <Dialog
    v-model="relateSelectDialogVisible"
    :title="t('cms.content.op.relate.select')"
    width="75%"
  >
    <div class="flex">
      <el-card class="w-1/5 user" :gutter="4" shadow="always">
        <el-button text key="primary" type="primary" @click="handleContentSelectAllClick">{{
          $t('cms.content.channel.allChannel')
        }}</el-button>

        <el-scrollbar height="650">
          <el-tree
            ref="contentSelectTreeRef"
            node-key="id"
            :default-expand-all="defaultExpandAll"
            :data="relateContentChannelOptions"
            :props="defaultProps"
            :highlight-current="true"
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            @node-click="handleContentSelectChannelNodeClick"
          />
        </el-scrollbar>
      </el-card>
      <!-- 列表 -->
      <el-card class="w-4/5 user" style="margin-left: 10px" :gutter="20" shadow="hover">
        <ContentWrap>
          <el-table
            :table-layout="tableLayout"
            v-loading="contentSelectLoading"
            :data="contentSelectList"
            ref="contentSelectTableRef"
            row-key="id"
            @selection-change="handleContentSelectionChange"
          >
            <el-table-column type="selection" />
            <el-table-column label="ID" align="center" prop="id" />
            <el-table-column label="标题" align="center" prop="title" />
            <el-table-column label="栏目" align="center" prop="channelName" />
            <el-table-column
label="发布时间"
              align="center"
              prop="releaseTime"
              :formatter="dateFormatter"
            />
            <el-table-column label="状态" align="center" prop="status">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.CMS_CONTENT_STATUS" :value="scope.row.status" />
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <Pagination
            :total="total"
            v-model:page="contentSelectQueryParams.pageNo"
            v-model:limit="contentSelectQueryParams.pageSize"
            @pagination="getContentSelectList"
          />
        </ContentWrap>
        <XButton
          type="primary"
          preIcon="ep:zoom-in"
          :title="t('action.add')"
          v-hasPermi="['cms:content-relate:create']"
          @click="submitRelateAdd()"
        />
      </el-card>
    </div>
  </Dialog>

  <!--内容版本分页弹窗-->
  <Dialog v-model="versionDialogVisible" :title="t('action.version')" width="50%">
    <ContentWrap>
      <XButton
        type="primary"
        preIcon="ep:zoom-in"
        :title="t('cms.content.op.version.savecurrent')"
        v-hasPermi="['cms:content-version:create']"
        @click="handleVersionCreate()"
      />
      <el-table
        v-loading="versionLoading"
        :table-layout="tableLayout"
        :data="versionDatas"
        ref="versionTableRef"
        row-key="id"
      >
        <el-table-column label="版本" align="center" prop="textVersion" />
        <el-table-column label="操作人员" align="center" prop="nickname" />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
        />
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <!-- 操作：版本比对 -->
            <XTextButton
              preIcon="ep:view"
              :title="t('cms.content.op.version.compare')"
              @click="handleVersionCompare(row.id)"
            />
            <!-- 操作：恢复版本 -->
            <XTextButton
              preIcon="ep:refresh"
              :title="t('action.restore')"
              @click="handleVersionRestore(row.id)"
            />
            <!-- 操作：删除数据 -->
            <XTextButton
              v-hasPermi="['cms:content-version:delete']"
              preIcon="ep:delete"
              :title="t('action.del')"
              @click="handleVersionDelete(row.id)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="relateTotal"
        v-model:page="relateQueryParams.pageNo"
        v-model:limit="relateQueryParams.pageSize"
        @pagination="getContentRelateList"
      />
    </ContentWrap>
  </Dialog>
  <!--内容版本对比弹窗-->
  <Dialog v-model="versionCompareDialogVisible" :title="t('action.version')" width="80%">
    <ContentWrap>
      <el-row>
          <el-col :span="12">历史版本</el-col>
          <el-col :span="12">当前版本</el-col>
      </el-row>
      <div>
        <Diff
          mode="split"
          theme="light"
          language="text"
          :prev=oldText
          :current=currText
          style="height: calc(100% - 50px); width: 100%; overflow: scroll"
        />
      </div>
    </ContentWrap>
  </Dialog>
</template>
<script setup lang="ts" name="Content">
// 全局相关的 import
import { ref } from 'vue'
import type { ElTree } from 'element-plus'
import { Top, DocumentCopy } from '@element-plus/icons-vue'
import { useI18n } from '@/hooks/web/useI18n'
import { dateFormatter } from '@/utils/formatTime'
import ContentForm from './ContentForm.vue'
import * as ContentApi from '@/api/cms/content'
import { getContentChannelTreeApi } from '@/api/cms/channel'
import { handleTree, defaultProps } from '@/utils/tree'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { listAllowPushSiteApi } from '@/api/cms/site'
import { listSimpleChannelApi } from '@/api/cms/channel'
import { ContentSelectPageVO } from '@/api/cms/content/types'
import { getSiteHeader } from '@/utils/cmscommon'
import { useUserStore } from '@/store/modules/user'


const { t } = useI18n() // 国际化
// const message = useMessage() // 消息弹窗
const defaultExpandAll = ref(false) //是否默认展开
const tableLayout = ref('auto')
const oldText = ref('')
const currText= ref('')

// 列表相关的变量
const queryParams = reactive({
  channelId: undefined,
  title: undefined,
  dictBlock: undefined,
  dictMark: undefined,
  topLevel: undefined,
  status: undefined,
  releaseTime: [],
  orderStrs: 'top_level_desc,release_time_desc,id_desc',
  pageNo: 1,
  pageSize: 20
})

const message = useMessage() // 消息
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryFormRef = ref() // 搜索的表单
const tableRef = ref() // 表格的 Ref
//const selectedIds = ref<number[]>([]) // 表格的选中 ID 数组

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ContentApi.getContentPageApi(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  tableRef.value.clearSelection()
  handleQuery()
}

//相关内容
const relateLoading = ref(true) // 列表的加载中
const relateTotal = ref(0) // 列表的总页数
const relateDatas = ref([]) // 列表的数据
const relateTableRef = ref() // 表格的 Ref
//const selectedIds = ref<number[]>([]) // 表格的选中 ID 数组

/** 查询相关内容列表 */
const getContentRelateList = async () => {
  relateLoading.value = true
  try {
    const data = await ContentApi.getContentRelatePageApi(relateQueryParams)
    relateDatas.value = data.list
    relateTotal.value = data.total
  } finally {
    relateLoading.value = false
  }
}

//相关内容选择
const contentSelectLoading = ref(true) // 列表的加载中
const contentSelectTotal = ref(0) // 列表的总页数
const contentSelectList = ref([]) // 列表的数据
const contentSelectTableRef = ref() // 表格的 Ref
// 列表相关的变量
const contentSelectQueryParams = reactive({
  channelId: undefined,
  title: undefined,
  status: undefined,
  pageNo: 1,
  pageSize: 20
})
const getContentSelectList = async () => {
  contentSelectLoading.value = true
  try {
    const data = await ContentApi.getContentPageApi(contentSelectQueryParams)
    contentSelectList.value = data.list
    contentSelectTotal.value = data.total
  } finally {
    contentSelectLoading.value = false
  }
}

const channel = ref<any>()
// 弹窗相关的变量
const modelVisible = ref(false) // 是否显示弹出层
const modelTitle = ref('edit') // 弹出层标题
const modelLoading = ref(false) // 弹出层loading
const actionType = ref('') // 操作按钮的类型
const formVisible = ref<boolean>(false)

const beanId = ref<number>()
const action = ref<'add' | 'edit' | 'copy' | 'review'>('edit')
// 左侧栏目树形结构
const channelOptions = ref<Tree[]>([])
const { push } = useRouter() // 路由
const treeRef = ref<InstanceType<typeof ElTree>>()
const getTree = async () => {
  const res = await getContentChannelTreeApi()
  channelOptions.value.push(...handleTree(res))
  relateContentChannelOptions.value.push(...handleTree(res))
}
const filterText = ref('')
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  const nameFilter = data.name.includes(value)
  const idFilter = Number(value) === data.id
  return nameFilter || idFilter
}

//折叠展开
const handleFoldAndExplain = () => {
  const nodesMap = treeRef.value!.store.nodesMap
  for (let key in nodesMap) {
    nodesMap[key].expanded = !defaultExpandAll.value
  }
  defaultExpandAll.value = !defaultExpandAll.value
}
//全部栏目点击
const handleSelectAllClick = async () => {
  //取消栏目选中
  queryParams.channelId = undefined
  treeRef.value!.setCurrentKey(undefined)
  channel.value = undefined
  await getList()
}
const handleChannelNodeClick = async (row: { [key: string]: any }) => {
  queryParams.channelId = row.id
  channel.value = row
  await getList()
}
const contentIds = ref<number[]>([]) // 表格的选中 ID 数组
/** 当内容主操作表格选择项发生变化时会触发该事件  */
const handleDataSelectionChange = (array: ContentSelectPageVO[]) => {
  contentIds.value = []
  if (!array) {
    return
  }
  array.forEach((row) => contentIds.value.push(row.id))
}

//执行批量内容操作
const submitBatch = async (action: string) => {
  if (contentIds.value.length === 0) {
    return
  }
  await handleBatchExecute(action, contentIds.value)
}

const handleBatchExecute = async (action: string, ids: number[]) => {
  //动作 删除 提交审核 下线 归档
  if (action === 'delete') {
    await ContentApi.deleteContentApi(ids)
    tableRef.value.clearSelection()
    handleQuery()
  } else if (action === 'twoDelete') {
    await ContentApi.twoDeleteContentApi(ids)
    tableRef.value.clearSelection()
    handleQuery()
  } else if (action === 'archive') {
    await ContentApi.archiveContentApi(ids)
    tableRef.value.clearSelection()
    handleQuery()
  } else if (action === 'offline') {
    await ContentApi.offlineContentApi(ids)
    tableRef.value.clearSelection()
    handleQuery()
  } else if (action === 'publish') {
    await ContentApi.publishContentApi(ids)
    tableRef.value.clearSelection()
    handleQuery()
  } else if (action === 'mark') {
    contentMark.ids = ids
    markDialogVisible.value = true
  } else if (action === 'block') {
    contentBlock.ids = ids
    blockDialogVisible.value = true
  } else if (action === 'move') {
    contentMove.ids = ids
    moveDialogVisible.value = true
  } else if (action === 'push') {
    contentPush.ids = ids
    pushDialogVisible.value = true
    pushTargetSites.value = await listAllowPushSiteApi()
  } else if (action === 'copy') {
    contentCopy.ids = ids
    copyDialogVisible.value = true
  } else {
    throw new Error(`not support action: ${action}`)
  }
}

// 设置标题
const setDialogTile = (type: string) => {
  modelLoading.value = true
  modelTitle.value = t('action.' + type)
  actionType.value = type
  modelVisible.value = true
}

// 新增操作
const handleCreate = () => {
  setDialogTile('create')
  modelLoading.value = false
  action.value = 'add'
  beanId.value = undefined
  console.log("channel.value->",channel.value)
  formVisible.value = true
}
const handleEdit = (id: number) => {
  action.value = 'edit'
  beanId.value = id
  formVisible.value = true
}
//移动
const moveDialogVisible = ref<boolean>(false)
const contentMove = reactive({
  ids: [0],
  targetChannelId: 0
})
//移动目标栏目选择
const handleMoveChannelNodeClick = async (row: { [key: string]: any }) => {
  contentMove.targetChannelId = row.id
}
//移动提交
const moveChannel = async () => {
  await ContentApi.moveContentApi(contentMove)
  message.success(t('common.success'))
  moveDialogVisible.value = false
  getList()
}
const handleMove = (ids: number[]) => {
  contentMove.ids = ids
  moveDialogVisible.value = true
}

//复制
const copyDialogVisible = ref<boolean>(false)
const contentCopy = reactive({
  ids: [0],
  targetChannelId: 0,
  pushType: 1
})
//复制目标栏目选择
const handleCopyChannelNodeClick = async (row: { [key: string]: any }) => {
  contentCopy.targetChannelId = row.id
}
//复制提交
const copySubmit = async () => {
  await ContentApi.copyContentApi(contentCopy)
  message.success(t('common.success'))
  copyDialogVisible.value = false
  getList()
}
const handleCopy = (ids: number[]) => {
  contentCopy.ids = ids
  copyDialogVisible.value = true
}

//推送
const pushDialogVisible = ref<boolean>(false)
const pushTargetSites = ref([])
const pushChannelOptions = ref<Tree[]>([])
const contentPush = reactive({
  ids: [0],
  targetChannelId: 0,
  targetSiteId: getSiteHeader(),
  targetStatus: 1,
  pushType: 1,
  pushPass: ''
})
//推送目标栏目选择
const handlePushChannelNodeClick = async (row: { [key: string]: any }) => {
  contentPush.targetChannelId = row.id
}
//推送提交
const pushSubmit = async () => {
  await ContentApi.pushContentApi(contentPush)
  message.success(t('common.success'))
  pushDialogVisible.value = false
  getList()
}
const handlePush = async (ids: number[]) => {
  contentPush.ids = ids
  pushDialogVisible.value = true
  pushTargetSites.value = await listAllowPushSiteApi()
}
const getPushChannelTree = async () => {
  const channels = await listSimpleChannelApi(contentPush.targetSiteId)
  pushChannelOptions.value = handleTree(channels)
}
//相关内容
const relateDialogVisible = ref<boolean>(false)
const relateQueryParams = reactive({
  contentId: 0,
  pageNo: 1,
  pageSize: 20
})
const relateSelectDialogVisible = ref<boolean>(false)

const handleRelate = async (id: number) => {
  relateQueryParams.contentId = id
  relateDialogVisible.value = true
  await getContentRelateList()
}
const contentSelectTreeRef = ref<InstanceType<typeof ElTree>>()
const relateContentChannelOptions = ref<Tree[]>([])

const handleRelateAdd = async () => {
  await getContentSelectList()
  relateSelectDialogVisible.value = true
}
const contentRelateData = reactive({
  relateIds: [0],
  contentId: 0
})

//相关内容弹窗栏目点击
const handleContentSelectChannelNodeClick = async (row: { [key: string]: any }) => {
  //取消栏目选中
  contentSelectQueryParams.channelId = row.id
  contentSelectTreeRef.value?.setCurrentKey(row.id)
  await getContentSelectList()
}

//相关内容弹窗全部栏目点击
const handleContentSelectAllClick = async () => {
  //取消栏目选中
  contentSelectQueryParams.channelId = undefined
  contentSelectTreeRef.value!.setCurrentKey(undefined)
  await getContentSelectList()
}

const contentSelectedIds = ref<number[]>([]) // 表格的选中 ID 数组
/** 当表格选择项发生变化时会触发该事件  */
const handleContentSelectionChange = (array: ContentSelectPageVO[]) => {
  contentSelectedIds.value = []
  if (!array) {
    return
  }
  array.forEach((row) => contentSelectedIds.value.push(row.id))
}
//执行添加相关内容
const submitRelateAdd = async () => {
  if (contentSelectedIds.value.length === 0) {
    return
  }
  await execRelateAdd(contentSelectedIds.value)
  contentSelectTableRef.value.clearSelection()
}
//执行添加相关内容
const execRelateAdd = async (ids) => {
  contentRelateData.relateIds = ids
  contentRelateData.contentId = relateQueryParams.contentId
  await ContentApi.addContentRelateApi(contentRelateData)
  relateSelectDialogVisible.value = false
  getContentRelateList()
}
const getRowIndex = (row) => {
  return relateDatas.value.findIndex((it: any) => it.id === row.id)
}
const getRowIndexIsEnd = (row) => {
  return relateDatas.value.findIndex((it: any) => it.id === row.id) == relateDatas.value.length - 1
}
const handleRelateUp = async (row, index, incre) => {
  const contentRelateSortData = {
    id: row.id,
    incre: incre,
    currIndex: index
  }
  await ContentApi.sortContentRelateApi(contentRelateSortData)
  getContentRelateList()
}
const contentRelateDeleteData = async (id:number) => {
  await ContentApi.deleteContentRelateApi(id)
  getContentRelateList()
}


//内容版本
const versionDialogVisible = ref<boolean>(false)
const versionQueryParams = reactive({
  contentId: 0,
  pageNo: 1,
  pageSize: 20
})
const handleVersion = async (id: number) => {
  versionQueryParams.contentId = id
  versionDialogVisible.value = true
  await getContentVersionList()
}
const versionLoading = ref(true) // 列表的加载中
const versionTotal = ref(0) // 列表的总页数
const versionDatas = ref([]) // 列表的数据
const versionTableRef = ref() // 表格的 Ref
const versionCompareDialogVisible = ref(false)
/** 查询内容版本列表 */
const getContentVersionList = async () => {
  versionLoading.value = true
  try {
    const data = await ContentApi.getContentVersionPageApi(versionQueryParams)
    versionDatas.value = data.list
    versionTotal.value = data.total
  } finally {
    versionLoading.value = false
  }
}
const handleVersionDelete = async (id:number) => {
  await ContentApi.deleteContentVersionApi(id)
  await getContentVersionList()
}
const handleVersionCreate = async () => {
  await ContentApi.createContentVersionApi(versionQueryParams.contentId)
  await getContentVersionList()
}
const handleVersionCompare = async (id: number) => {
  const oldVersion = await ContentApi.getContentVersionApi(id)
  oldText.value = oldVersion.plainText
  const currVersion = await ContentApi.getContentApi(versionQueryParams.contentId)
  currText.value = currVersion.plainText
  versionCompareDialogVisible.value = true
}
const handleVersionRestore = async (id: number) => {
  await ContentApi.restoreContentVersionApi(id)
  versionCompareDialogVisible.value = false
  versionDialogVisible.value = false
  ElMessage.success(t('common.success'))
}
//标记 设置区块
const contentMarks = ref()
const contentBlocks = ref()
const contentPushTypes = ref()
const contentStatus = ref()
const init = () => {
  contentMarks.value = getIntDictOptions(DICT_TYPE.CMS_CONTENT_MARKS)
  contentBlocks.value = getIntDictOptions(DICT_TYPE.CMS_CONTENT_BLOCKS)
  contentPushTypes.value = getIntDictOptions(DICT_TYPE.CMS_CHANNEL_RULE_COLL_TYPE)
  contentStatus.value = getIntDictOptions(DICT_TYPE.CMS_CONTENT_STATUS)
}
//标记
const markDialogVisible = ref<boolean>(false)
const contentMark = reactive({
  ids: [0],
  dictMark: undefined
})
//标记提交
const markContent = async () => {
  await ContentApi.markContentApi(contentMark)
  message.success(t('common.success'))
  markDialogVisible.value = false
  getList()
}
const handleMark = async (ids: number[]) => {
  contentMark.ids = ids
  //这里兼容下单条设置
  if (ids.length == 1) {
    const content = await ContentApi.getContentApi(ids[0])
    contentMark.dictMark = content.dictMark
  }
  markDialogVisible.value = true
}

//区块设置
const blockDialogVisible = ref<boolean>(false)
const contentBlock = reactive({
  ids: [0],
  dictBlock: undefined
})
const blockContent = async () => {
  await ContentApi.blockContentApi(contentBlock)
  message.success(t('common.success'))
  blockDialogVisible.value = false
  getList()
}
const handleBlock = async (ids: number[]) => {
  contentBlock.ids = ids
  //这里兼容下单条设置
  if (ids.length == 1) {
    const content = await ContentApi.getContentApi(ids[0])
    contentBlock.dictBlock = content.dictBlock
  }
  blockDialogVisible.value = true
}
const handleDelete = (ids: number[]) => {
  handleExecute('delete', ids)
}
const handleTwoDelete = (ids: number[]) => {
  handleExecute('twoDelete', ids)
}
const handlePublish = (ids: number[]) => {
  handleExecute('publish', ids)
}

const handleOffline = (ids: number[]) => {
  handleExecute('offline', ids)
}

const handleArchive = (ids: number[]) => {
  handleExecute('archive', ids)
}

const handleExecute = async (action: string, ids: number[]) => {
  if (action === 'delete') {
    await ContentApi.deleteContentApi(ids)
  } else if (action === 'twoDelete') {
    await ContentApi.twoDeleteContentApi(ids)
  } else if (action === 'submit') {
    await ContentApi.submitContentApi(ids)
  } else if (action === 'archive') {
    await ContentApi.archiveContentApi(ids)
  } else if (action === 'offline') {
    await ContentApi.offlineContentApi(ids)
  } else if (action === 'publish') {
    await ContentApi.publishContentApi(ids)
  } else if (action === 'completelyDelete') {
    await ContentApi.twoDeleteContentApi(ids)
  } else {
    throw new Error(`not support action: ${action}`)
  }
  getList()
  message.success(t('common.success'))
}
//处理置顶
const handleTop = async (ids: number[], topLevel: number) => {
  try {
    const { value } = await ElMessageBox.prompt(
      `${t('cms.content.topLevel')} (${t('cms.content.topLevel.tooltip')})`,
      {
        confirmButtonText: t('common.ok'),
        cancelButtonText: t('common.cancel'),
        inputValue: String(topLevel < 1 ? 0 : topLevel),
        inputPattern: /^\d{1,2}$/,
        inputErrorMessage: t('cms.content.error.topLevel')
      }
    )
    await ContentApi.topContentApi(ids, Number(value))
    getList()
    ElMessage.success(t('common.success'))
  } catch (e) {
    /* empty */
  }
}
// 处理审批按钮
const handleAudit = (row) => {
  push({
    name: 'BpmProcessInstanceCustomDetail',
    query: {
      id: row.processInstanceId
    }
  })
}

//保存后回调
const finishAndReload = () => {
  formVisible.value = false
  getList()
}

// ========== 初始化 ==========
onMounted(async () => {
  await getTree()
  await getPushChannelTree()
  //取字典区块 标记数据
  await init()
  await getList()
})
</script>
